import styles from './login.module.scss'
import React, { useState, useEffect } from 'react'
import classNames from 'classnames'
import { Checkbox, Flex, message, Modal } from 'antd'
import OtherLogin from '@/components/other-login/other-login'
import type { CheckboxProps } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'
import { useDispatch } from 'react-redux'

import logoPath from '@/assets/img/gg-exam-logo.png'
import { login, verification } from '@/api/user'
import { targetUrl } from '@/utils/config'

const Login: React.FC = () => {
  interface loginInfoType {
    account: string
    password: string
  }
  /**
   * 变量集合 在es6中 const let 是有块级作用域的所以，最好就把变量什么放到最前面 避免变量提升引发的错误
   */
  const StorageLoginInfo = localStorage.getItem('loginInfo')
  const LoginInfo: loginInfoType = StorageLoginInfo ? JSON.parse(StorageLoginInfo) : { account: '', password: '' }
  const [pwdLogin, setPwdLogin] = useState(true) // tab栏相关变量
  const [messageApi, contextHolder] = message.useMessage() //消息提示框
  const [account, setAccount] = useState(StorageLoginInfo ? LoginInfo.account : '') // 账号
  const [password, setPassword] = useState(StorageLoginInfo ? LoginInfo.password : '') // 密码
  const [isModalOpen, setIsModalOpen] = useState(false) // 对话框
  const [errorMsg, setErrorMsg] = useState('') // 错误信息
  const location = useLocation() // 路由信息
  const navigate = useNavigate() // 路由跳转
  const [isRemember, setIsRemember] = useState(Boolean(localStorage.getItem('remember') === 'true' ? localStorage.getItem('remember') : false)) // 是否记住密码
  // const { token } = useSelector((state: RootState) => state.handleUser)
  // 这种可以把多个不同的state导出来 但是可能会引来警告 Selector unknown returned the root state when called.
  // const { token } = useSelector((state: RootState) => ({
  //   token: state.handleUser.token
  // })) // store reducx
  const dispatch = useDispatch() // store reducx
  const [verificationCode, setVerificationCode] = useState('')
  const [userAgent, setUserAgent] = useState('')
  const [img_key, setimg_key] = useState(0)

  /**
   * 页面加载完成时 只执行一次
   */
  useEffect(() => {
    const userAgent = navigator.userAgent
    setUserAgent(userAgent)
  }, [])

  /**
   * tab栏相关
   */
  function changTab() {
    // 如需要立即获取到修改的结果，需要在useEffect中进行
    setPwdLogin(!pwdLogin)
  }
  useEffect(() => {
    if (!pwdLogin) {
      messageApi.open({
        type: 'warning',
        content: '开发中'
      })
      setPwdLogin(!pwdLogin)
    }
  }, [pwdLogin, messageApi])

  /**
   * 记住我
   */
  const remember: CheckboxProps['onChange'] = e => {
    setIsRemember(e.target.checked)
    localStorage.setItem('remember', String(e.target.checked))
  }

  /**
   * 登陆
   */
  const _login = async (event: React.FormEvent) => {
    event.preventDefault() // 阻止默认行为，即阻止页面刷新

    // 是否记住了密码
    if (isRemember) {
      const loginInfo = {
        account: account,
        password: password
      }
      localStorage.setItem('loginInfo', JSON.stringify(loginInfo))
    } else {
      localStorage.removeItem('loginInfo')
    }

    if (verificationCode === '') {
      return messageApi.open({
        type: 'error',
        content: '请输入验证码'
      })
    }
    if (!account || !password) {
      return messageApi.open({
        type: 'error',
        content: '账号或密码不可为空'
      })
    }

    //验证 验证码
    const v_res = await verification({ code: verificationCode, userAgent: userAgent })

    if (v_res.code === 400 || v_res.message === '验证码错误') {
      return messageApi.open({
        type: 'error',
        content: '验证码错误'
      })
    }

    const res = await login({ account: account, password: password })
    if (typeof res.message === 'object') {
      res.message = JSON.stringify(res.message)
    }

    if (res.code > 299 || res.code < 200) {
      setIsModalOpen(true)
      setErrorMsg(`${res.message}`)
      return
    }
    dispatch({ type: 'setToken', val: res.data.token })
    dispatch({ type: 'setUserInfo', val: res.data.userinfo })
    messageApi.open({
      type: 'success',
      content: '登陆成功'
    })
    const toPath = location.state ? location.state.from : 'home'

    setTimeout(() => {
      toPath === 'login' ? navigate('/home', { replace: true }) : navigate(`/${toPath}`, { replace: true })
    }, 500)
  }

  /**
   * 对话框相关
   */
  const handleOk = () => {
    setIsModalOpen(false)
  }
  const handleCancel = () => {
    setIsModalOpen(false)
  }

  /**
   *
   */
  const reLoadImage = () => {
    setimg_key(prevKey => prevKey + 1)
  }

  return (
    <>
      {contextHolder}
      {/* 提示框 */}
      <Modal title="提示" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <p>{errorMsg}</p>
      </Modal>
      {/* 内容 */}
      <div className={styles.box_login}>
        <div className={styles.login}>
          <div className={styles.title}>
            <div className={styles.logo}>
              <img src={logoPath} alt="GG题库" />
            </div>
            GG题库用户登陆
          </div>
          <div className={styles.tab}>
            <div className={classNames(styles.tab_item, styles.password, { [styles.selected_tab_item]: pwdLogin })} onClick={changTab}>
              密码登陆
            </div>
            <div className={classNames(styles.tab_item, styles.message, { [styles.selected_tab_item]: !pwdLogin })} onClick={changTab}>
              短信登陆
            </div>
          </div>
          {/* 表单 */}
          <form onSubmit={_login}>
            {/* 账号密码 */}
            <div className={classNames(styles.username, styles.input_box)}>
              <input type="text" placeholder="手机号/邮箱" value={account} onChange={e => setAccount(e.target.value)} />
            </div>
            <div className={classNames(styles.password, styles.input_box)}>
              <input type="password" placeholder="密码" value={password} onChange={e => setPassword(e.target.value)} />
            </div>
            {/* 验证码 */}
            <div className={classNames(styles.box_verification)}>
              <input type="text" placeholder="请输入验证码" value={verificationCode} onChange={e => setVerificationCode(e.target.value)} />
              <img key={img_key} src={targetUrl + ':9002' + '/java/api/v1/captcha?userAgent=' + userAgent} alt="" onClick={reLoadImage} />
            </div>
            {/* 记住我 忘记密码 */}
            <div className={classNames(styles.box_func)}>
              <Flex vertical={false} align={'center'} justify={'space-between'}>
                <Checkbox checked={isRemember} onChange={remember}>
                  记住我
                </Checkbox>
                <div className={classNames(styles.forget)} style={{ cursor: 'pointer' }}>
                  忘记密码
                </div>
              </Flex>
            </div>

            {/* 登陆按钮 */}
            <div className={classNames(styles.box_btn)}>
              <button type="submit" className={classNames(styles.btn_login)} onClick={_login}>
                登陆
              </button>
            </div>
            <OtherLogin flag={'login'} />
          </form>
        </div>
      </div>
    </>
  )
}

export default Login
